use std::collections::HashMap;

use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::{error::Error, modeling::Value};

use super::ClassAttributePersistence;

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "ClassPersistenceBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct ClassPersistence {
    //
    pub class_identifier: String,

    pub table_name: String,

    pub columns: Vec<ClassAttributePersistence>,

    pub options: String,
}

impl TryFrom<Value> for ClassPersistence {
    type Error = anyhow::Error;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        let v: serde_json::Value = value.try_into()?;
        Ok(serde_json::from_value(v).map_err(|err| anyhow::anyhow!("{}", err))?)
    }
}

impl TryInto<Value> for ClassPersistence {
    type Error = anyhow::Error;

    fn try_into(self) -> Result<Value, Self::Error> {
        Ok(serde_json::to_value(self)
            .map_err(|err| anyhow::anyhow!("{}", err))?
            .try_into()?)
    }
}
